//
//  SRBookCatalogueListViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/4/18.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRBookCatalogueListViewController.h"

#import "SRBookCatalogueUnitSectionModel.h"
#import "SRBookCatalogueModel.h"

#import "SRBookCatalogueSectionHeaderView.h"
#import "SRBookCatalogueListTableViewCell.h"

@interface SRBookCatalogueListViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *sectionItems;//分段数组


@end

@implementation SRBookCatalogueListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupData];
    [self setupView];
    
    self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
    [self setupNavigationBarButtonItem];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - init 

- (void)setupData {
    self.sectionItems = [@[] mutableCopy];
    if (self.catalogues && [self.catalogues count] > 0) {
        NSString *lastUint = nil;
        SRBookCatalogueUnitSectionModel *sectionModel = nil;
        for (int i = 0; i < [self.catalogues count]; ++ i) {
            SRBookCatalogueModel *item = [self.catalogues objectAtIndex:i];
//            NSLog(@"sort Item Unit:%@", item.unit);
            if (!sectionModel || !lastUint || ![lastUint isEqualToString:item.unit]) {
                lastUint = item.unit;
                if (sectionModel) {
                    [self.sectionItems addObject:sectionModel];
                }
                sectionModel = [[SRBookCatalogueUnitSectionModel alloc] init];
                sectionModel.unit = item.unit;
                [sectionModel.catalogueLists addObject:item];
            } else {
                [sectionModel.catalogueLists addObject:item];
            }
            
            if (i == ([self.catalogues count] - 1) && sectionModel) {
                    //最后一个
                [self.sectionItems addObject:sectionModel];
            }
        }
    }
}


- (void)setupNavigationBarButtonItem {
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"目录";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [FZStyleSheet currentStyleSheet].fontOfH2;
    
    [self.view addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(20);
        make.height.mas_equalTo(44);
        make.centerX.equalTo(self.view);
    }];
    
    UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setTitle:@"关闭" forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    rightButton.frame = CGRectMake(0, 0, 44, 44);
    rightButton.titleLabel.font = [FZStyleSheet currentStyleSheet].fontOfH2;
    [rightButton addTarget: self action: @selector(onCloseButton:) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview:rightButton];
    
    [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(20);
        make.trailing.equalTo(self.view).offset(-20);
        make.width.height.mas_equalTo(44);
    }];
    
//    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
//    [self setRightBarButtonItem:rightBarItem];
}
- (void)setupView {
    
//    WEAKSELF
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 50;
    [self.tableView registerClass:[SRBookCatalogueSectionHeaderView class] forHeaderFooterViewReuseIdentifier:kSRBookCatalogueSectionHeaderView];
    
    [self.tableView registerNib:[UINib nibWithNibName:kSRBookCatalogueListTableViewCell bundle:nil] forCellReuseIdentifier:kSRBookCatalogueListTableViewCell];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.separatorColor = css.color_4;
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0 , 0);
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(65);
        make.leading.trailing.bottom.equalTo(self.view);
    }];
    self.tableView.backgroundColor = [UIColor clearColor];
}


#pragma mark - Event 

- (void)onCloseButton:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.sectionItems count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section >= [self.sectionItems count]) {
        return 0;
    }
    
    SRBookCatalogueUnitSectionModel *sectionModel = self.sectionItems[section];
    
    if (sectionModel.catalogueLists) {
        return [sectionModel.catalogueLists count];
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SRBookCatalogueListTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kSRBookCatalogueListTableViewCell forIndexPath:indexPath];

    if (indexPath.section < [self.sectionItems count]) {
        SRBookCatalogueUnitSectionModel *sectionModel = self.sectionItems[indexPath.section];
        SRBookCatalogueModel *model = nil;
        
        if ([sectionModel.catalogueLists count] > indexPath.row) {
            model = sectionModel.catalogueLists [indexPath.row];
            cell.titleLabel.text = model.title;
            cell.pageLabel.text = [NSString stringWithFormat:@"第%d页", (int)[model.page integerValue]];
        }
    }
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
        //若没有数据的段，需要隐藏头部高度
    CGFloat defaultHeight = 15;
    if (section < [self.sectionItems count]) {
        SRBookCatalogueUnitSectionModel *sectionModel = self.sectionItems[section];
        if ([sectionModel.catalogueLists count] > 0) {
            return defaultHeight;
        }
    }
    return 0.001;//需要隐藏
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    CGFloat defaultHeight = 50;    
    return 10;//需要隐藏
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section < [self.sectionItems count]) {
        SRBookCatalogueUnitSectionModel *sectionModel = self.sectionItems[section];
        if ([sectionModel.catalogueLists count] > 0) {
            SRBookCatalogueSectionHeaderView *sectionHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kSRBookCatalogueSectionHeaderView];
            sectionHeaderView.titleLabel.text = [NSString stringWithFormat:@"%@", sectionModel.unit];
            
            return sectionHeaderView;
        }
    }
    
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return nil;
}
#pragma mark - UITableViewDelegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section < [self.sectionItems count]) {
        SRBookCatalogueUnitSectionModel *sectionModel = self.sectionItems[indexPath.section];
        if ([sectionModel.catalogueLists count] > indexPath.row) {
            SRBookCatalogueModel *model = sectionModel.catalogueLists[indexPath.row];
            
            [self dismissViewControllerAnimated:YES completion:^{
                if (self.didSelectedCatalogueBlock) {
                    self.didSelectedCatalogueBlock(model);
                }
            }];
            
        }
    }
}


@end
